﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using Thaire.Investment.Common;
//using ThaireInvestmentWeb.BusinessDelegate;
using ThaireInvestmentWeb.Models;
using ThaireInvestmentWeb.Util;
using ThaireInvestmentWeb.WcfSerivce;

namespace ThaireInvestmentWeb.Controllers
{
    public class FixedIncomeController : Controller
    {
        //
        // GET: /Instrument/

        // String UserLogin = "TestUser2";

        //private ServiceDelegate _service;
        //public ServiceDelegate Service
        //{
        //    get { return _service ?? (_service = new ServiceDelegate()); }
        //}


        public ActionResult Index()
        {
            return View();
        }


        #region FixedIncomeSecurities

        #region Guarantee
        //public ActionResult FixedIncomeGuarantee(int purchaseID)
        //{
        //    var data = Service.GetFixIncomeSecuritiesTransactionScreenData(purchaseID);
        //    var model = FixedIncomeGuaranteeModel.Build(data);
        //    TempData["FixedIncomeGuaranteeModel"] = model;
        //    return View(model);
        //}
        public ActionResult FixedIncomeGuarantee(int purchaseID, int? transactionID)
        {
            var data = ServiceFactory.GetService().GetFixIncomeSecuritiesTransactionScreenData(purchaseID, transactionID);
            var model = FixedIncomeGuaranteeModel.Build(data);
            if (transactionID.HasValue)
            {
                model.UpdateMode = true;
            }
            TempData["FixedIncomeGuaranteeModel"] = model;
            return View(model);
        }

        [HttpPost]
        public ActionResult FixedIncomeGuarantee(FixedIncomeGuaranteeModel model)
        {
            var oldModel = (FixedIncomeGuaranteeModel)TempData["FixedIncomeGuaranteeModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.BtnSave))
                    {
                        var operationData = model.ToFixIncomeSecuritiesTransaction();
                        oldModel.BookCount = model.BookCount;
                        oldModel.StartDate = model.StartDate;
                        oldModel.EndDate = model.EndDate;
                        oldModel.Unit = model.Unit;
                        if (model.UpdateMode)
                        {
                            oldModel.SetFixIncomeSecuritiesTransaction(
                                ServiceFactory.GetService().UpdateFixIncomeSecuritiesTransaction(operationData));
                        }
                        else
                        {
                            operationData.CreateUserId = SessionManager.UserID(Session);
                            oldModel.SetFixIncomeSecuritiesTransaction(
                                ServiceFactory.GetService().InsertFixIncomeSecuritiesTransaction(operationData));
                        }
                        oldModel.UpdateMode = true;
                        ModelState.Clear();
                       // ViewBagUtil.SetInfo(ViewBag, "การทำงานสมบูรณ์", "EditPurchase?purchaseID=" + model.PurcheseID);
                        ViewBagUtil.SetInfo(ViewBag, "การทำงานสมบูรณ์", null);

                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }

                }
                catch (Exception ex)
                {
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["FixedIncomeGuaranteeModel"] = oldModel;
            return View(oldModel);
        }

        #endregion

        #region Sale
        /// <summary>
        /// init sale ,update mode sale
        /// </summary>
        /// <param name="purchaseID"></param>
        /// <param name="transactionID"></param>
        /// <returns></returns>
        public ActionResult FixedIncomeSale(int purchaseID, int? transactionID)
        {
            FixIncomeSecuritiesTransactionScreenData data = ServiceFactory.GetService().GetFixIncomeSecuritiesTransactionScreenData(purchaseID, transactionID);
            FixedIncomeSaleModel model = FixedIncomeSaleModel.Build(data);
            if (transactionID.GetValueOrDefault() != 0)
            {
                model.UpdateMode = true;
            }
            TempData["FixedIncomeSaleModel"] = model;
            return View(model);
        }

        //public ActionResult EditFixedIncomeSale(int purchaseID,int transactionID)
        //{
        //    FixIncomeSecuritiesTransactionScreenData data = Service.GetFixIncomeSecuritiesTransactionScreenData(purchaseID, transactionID);
        //    FixedIncomeSaleModel model = FixedIncomeSaleModel.Build(data);
        //    TempData["FixedIncomeSaleModel"] = model;
        //    return View(model);
        //}
        public ActionResult FixedIncomeSaleFormAction(FixedIncomeSaleModel model)
        {
            FixedIncomeSaleModel oldModel = (FixedIncomeSaleModel)TempData["FixedIncomeSaleModel"];
            if (ModelState.IsValid)
            {
               // ServiceDelegate service = new ServiceDelegate();
                try
                {
                    if (!String.IsNullOrEmpty(model.BtnSave))
                    {
                        FixIncomeSecuritiesTransaction operationData = model.ToFixIncomeSecuritiesTransaction();
                        CounterParties counter =
                            oldModel.ScreenData.CounterParties.Where(
                                x => x.CounterpartiesId == operationData.CounterpartyID.GetValueOrDefault()).
                                SingleOrDefault();
                        if (counter != null)
                            operationData.CounterpartyName = counter.CounterpartiesCodeName;
                        PaymentType payment = oldModel.ScreenData.TypeOfPayment.Where(x => x.PaymentTypeId == operationData.TypeofpaymentID.GetValueOrDefault()).SingleOrDefault();
                        if (payment != null)
                            operationData.TypeofpaymentName = payment.PaymentTypeName;
                        FixIncomeSecuritiesTransaction result = null;
                        oldModel.SetFixIncomeSecuritiesTransaction(operationData);//set new Data to oldeModel for render Data
                        if (model.UpdateMode)
                        {
                            result = ServiceFactory.GetService().UpdateFixIncomeSecuritiesTransaction(operationData);

                        }
                        else
                        {
                            operationData.CreateUserId = SessionManager.UserID(Session);
                            result = ServiceFactory.GetService().InsertFixIncomeSecuritiesTransaction(operationData);
                        }
                        oldModel.SetFixIncomeSecuritiesTransaction(result);
                        oldModel.UpdateMode = true;
                        ModelState.Clear();
                        return RedirectToAction("FixedIncomeSale", new { purchaseID = result.PurchaseID, transactionID = result.TransactionID });//. .PurcheseID,oldModel.tr
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);

                }
                //FixIncomeSecuritiesTransactionScreenData data = service.GetFixIncomeSecuritiesTransactionScreenData(purchaseID);
                //FixedIncomeSaleModel model = FixedIncomeSaleModel.Build(data);
            }
            TempData["FixedIncomeSaleModel"] = oldModel;
            return View("FixedIncomeSale", oldModel);
        }

        public ActionResult GetInvolvedType(int id)
        {
            AddFixedIncomeModel model = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];

            InvolvedPartyType involve = model.ScreenData.InvolvedPartyType.Where(X => X.InvolvedPartyTypeId == id).SingleOrDefault();
            TempData["AddFixedIncomeModel"] = model;
            if (involve != null)
            {
                return Json(new { InvolvedPartyTypeReference = involve.InvolvedPartyTypeReference, InvolvedPartyTypeCode = involve.InvolvedPartyTypeCode });
            }
            else
            {
                return Json(new { InvolvedPartyTypeReference = "", InvolvedPartyTypeCode = "" });
            }
        }
        public ActionResult GetForeign(string creditagencyID)
        {
            AddFixedIncomeModel oldModel = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];

          //  CreditAgency data = oldModel.ScreenData.CreditAgency.Where(x => x.CreditAgencyID == DataConverter.ConvertStringToIntNull(creditagencyID).GetValueOrDefault()).FirstOrDefault();
            CreditAgency data = oldModel.ScreenData.CreditAgency.Where(x => x.CreditAgencyIssue == creditagencyID).FirstOrDefault();
            
            TempData["AddFixedIncomeModel"] = oldModel;
            if (data != null)
            {
                 return Json(new { AgencyCountry =data.CreditAgencyCountry});
            }else{
                 return Json(new { AgencyCountry =String.Empty});
            }



        }
        public ActionResult GetMaturityStatus(DateTime? maturityDate, DateTime? issueDate)
        {
            AddFixedIncomeModel oldModel = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];
            String issueTerm = string.Empty;
            double? year = Calculator.CalFixIncomeIssueTerm(maturityDate, issueDate);
            if(year.HasValue)
            {
                issueTerm = year.GetValueOrDefault().ToString("0.00");
            }
           // String issueTerm = Calculator.CalFixIncomeIssueTerm(maturityDate, issueDate).;
            //double year = Calculator.CalFixIncomeIssueTerm(maturityDate, issueDate);
            //if (year < 0)
            //    issutTerm = "N/A";
            //else
            //    issutTerm = year.ToString("0.00");


            TempData["AddFixedIncomeModel"] = oldModel;
            if (maturityDate.GetValueOrDefault().Date >= DateTime.Now.Date)

                return Json(new { MaturityStatus = "Matured", IssuerTermDsp = issueTerm });
            else
                return Json(new { MaturityStatus = "Alive", IssuerTermDsp = issueTerm });
        }
        #endregion

        #region header
         public ActionResult AmortizeSchedule(int headerID,int? page)
        {
            AmortizeScheduleModel model = null;
            try
            {
                if (page.HasValue)
                {
                    model = (AmortizeScheduleModel)TempData["AmortizeScheduleModel"];
                }
                else
                {
                    var data = ServiceFactory.GetService().GetAmortizeScheduleScreenData(headerID);
                    model = AmortizeScheduleModel.Build(data);
                    model.HeaderID = headerID;
                }
            }
            catch (Exception ex)
            {
                model = new AmortizeScheduleModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["AmortizeScheduleModel"] = model;
            return View(model);
         }
         public ActionResult DeleteAmortizeSchedule(int deleteID)
         {
             AmortizeScheduleModel oldModel = (AmortizeScheduleModel)TempData["AmortizeScheduleModel"];
             try
             {
                 ServiceFactory.GetService().DeleteAmortizeSchedule(deleteID);
                 var delItem = oldModel.ScheduleList.Where(x => x.FixincomesecuritiesAmortizeScheduleID == deleteID).SingleOrDefault();
                 if (delItem != null)
                 {
                     oldModel.ScheduleList.Remove(delItem);
                 }
             }
             catch (Exception ex)
             {
                   ViewBagUtil.SetError(ViewBag, ex.Message, null);
             }

             TempData["AmortizeScheduleModel"] = oldModel;

             return RedirectToAction("AmortizeSchedule", "FixedIncome", new { headerID = oldModel.HeaderID, page = 0});
         }
        [HttpPost]
         public ActionResult AmortizeSchedule(AmortizeScheduleModel model)
         {
             AmortizeScheduleModel oldModel = (AmortizeScheduleModel)TempData["AmortizeScheduleModel"] ;
          
           try
           {
               var service = ServiceFactory.GetService();
               if (!String.IsNullOrEmpty(model.BtnSubmit))
               {
                   FixincomesecuritiesAmortizeSchedule data = new FixincomesecuritiesAmortizeSchedule();
                   data.CreateBy = SessionManager.UserID(Session);
                   data.PaymentDate = model.PaymentDate;
                   data.Payment = model.AmortizingPayment;
                   data.FixincomesecuritiesHeaderID = model.HeaderID;
                   data = service.InsertAmortizeSchedule(data);

                   oldModel.ScheduleList.Add(data);
                   ModelState.Clear();
               }
               //else if (model.DeleteID.HasValue)
               //{
               //    service.DeleteAmortizeSchedule(model.DeleteID.Value);
               //    var delItem = oldModel.ScheduleList.Where(x => x.FixincomesecuritiesAmortizeScheduleID == model.DeleteID.Value).SingleOrDefault();
               //    if (delItem != null)
               //    {
               //        oldModel.ScheduleList.Remove(delItem);
               //    }
               //    ModelState["DeleteID"].Value = null;//clear stage
               //}
               //else
               //{
               //    ViewBagUtil.SetError(ViewBag, "Unknow Operation", null);
               //}
           }
           catch (Exception ex)
           {

               ViewBagUtil.SetError(ViewBag, ex.Message, null);
           }

             TempData["AmortizeScheduleModel"] = oldModel;
             return RedirectToAction("AmortizeSchedule", "FixedIncome", new { headerID = oldModel.HeaderID, page = 0 });
          //   return View(oldModel);
         }
        /// <summary>
        /// หน้า manage เมนู FixedIncomeSecurittes
        /// </summary>
        /// <returns></returns>
        public ActionResult ManageFixedIncomeSecurittes()
        {
         

            SearchFixedIncomeSecuritiesModel model = null;
            try
            {
                var data = ServiceFactory.GetService().GetFixedIncomeListScreenData();
                model = SearchFixedIncomeSecuritiesModel.BuildFixedIncomeModel(data);
            }
            catch (Exception ex)
            {
                model = new SearchFixedIncomeSecuritiesModel();
                //   ViewData["error"] = ex.Message;
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
                //  ModelState.AddModelError("", ex.Message);
            }
            TempData["SearchFixedIncomeSecuritiesModel"] = model;
            return View(model);
        }

      

        /// <summary>
        /// ค้นหา Header
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SearchFormAction(SearchFixedIncomeSecuritiesModel model)
        {
            // ViewBag.MyScreenModel = model;
            var oldModel = (SearchFixedIncomeSecuritiesModel)TempData["SearchFixedIncomeSecuritiesModel"];
            
            try
            {
                oldModel.SelectedCompany = model.SelectedCompany;
                oldModel.SelectedIssuer = model.SelectedIssuer;
                oldModel.SelectedIssuerType = model.SelectedIssuerType;
                oldModel.Symbol = model.Symbol;
                oldModel.IssueTerm = model.IssueTerm;

                if (!String.IsNullOrEmpty(model.SearchBtn))
                {
                    oldModel.Result = SearchFixedIncomeSecurities(oldModel);
                    if (oldModel.Result == null || oldModel.Result.Count == 0)
                    {
                        ViewBagUtil.SetInfo(ViewBag, "ไม่พบข้อมูล", null);

                    }
                }
                else if (!String.IsNullOrEmpty(model.ResetBtn))
                {
                    ModelState.Clear();
                    oldModel.ClearFilterAndData();
                }
               
            }
            catch (Exception ex)
            {
                //   ViewData["error"] = ex.Message;
                ViewBagUtil.SetInfo(ViewBag, ex.Message, null);
                // ModelState.AddModelError("", ex.Message);
            }
            //return View("fixedIncomeLIst", oldModel);
            TempData["SearchFixedIncomeSecuritiesModel"] = oldModel;
            return View("ManageFixedIncomeSecurittes", oldModel);
        }

        /// <summary>
        /// หน้า add header
        /// </summary>
        /// <returns></returns>
        public ActionResult AddfixedIncome()
        {
           // var service = new ServiceDelegate();
            var scrData = ServiceFactory.GetService().GetFixedIncomeHeaderScreenData();
            var model = AddFixedIncomeModel.BuildModel(scrData);
            TempData["AddFixedIncomeModel"] = model;
            return View(model);
        }

        /// <summary>
        /// หน้า edit header
        /// </summary>
        /// <param name="fixedincomeID"></param>
        /// <returns></returns>
        public ActionResult EditFixedIncome(int fixedincomeID)
        {
            ModelState.Clear();
            if (fixedincomeID == 0)
            {
                return RedirectToAction("AddfixedIncome");

            }
            else
            {
               // var service = new ServiceDelegate();
                var scrData = ServiceFactory.GetService().GetFixedIncomeHeaderScreenData();

                scrData.FixIncomeSecuritiesDTO = ServiceFactory.GetService().GetFixIncomeHeaderByID(fixedincomeID);
                var model = AddFixedIncomeModel.BuildModel(scrData);
                model.UpdateMode = true;
                TempData["AddFixedIncomeModel"] = model;
                return View("AddfixedIncome", model);
            }
        }

        /// <summary>
        /// ค้นหา header
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private IList<FixIncomeSecuritiesHeader> SearchFixedIncomeSecurities(SearchFixedIncomeSecuritiesModel model)
        {
            return ServiceFactory.GetService().SearchFiexdIncome(model.ToSearchFiexdIncomeFilter());
        }
        public ActionResult GetRatingHistory(int? page)
        {
            var oldData = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];
            TempData["AddFixedIncomeModel"] = oldData;
            RatingHistoryViewDTO [] data = ServiceFactory.GetService().GetRatingHistory(oldData.Data.FixincomesecuritiesHeaderId,"FIXINCOMESECURITIES");

            return View("_RatingHistoryPopup", data);
        }

        public ActionResult GetRiskLevel(String issueRating, String issueAgency, String issuerRating, String issuerAgency, String gurantRating, String gurantAgency)
        {
            RatingHistory rate = new RatingHistory();



            var oldData = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];
            TempData["AddFixedIncomeModel"] = oldData;
            rate.IssueRating = issueRating;
             rate.IssuerRating = issuerRating;
             rate.GuarantorRating = gurantRating;


            rate.IssueCreditAgency = issueAgency;
            rate.IssuerCreditAgency = issuerAgency;
            rate.GuarantorCreditAgency = gurantAgency;
            int? risk = ServiceFactory.GetService().GetRiskLevel(rate);
            if (risk.HasValue)
            {
                return Json(new { RiskLevel = risk.GetValueOrDefault() });
            }
            else
            {
                return Json(new { RiskLevel = "" });
            }
        }

        /// <summary>
        /// action สำหรับ insert or update header
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult AddfixedIncomeFormAction(AddFixedIncomeModel model, int? page)
        {

            var oldData = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];
            TempData["AddFixedIncomeModel"] = oldData;

            CopyNewHeaderDataToOldModel(model);
            if (!String.IsNullOrEmpty(model.SaveBtn))
            {

                if (model.Data.LiquidityTierIiPercent.GetValueOrDefault() +
                    model.Data.LiquidityTierIPercent.GetValueOrDefault() +
                    model.Data.LiquidityLowLiquidityPercent.GetValueOrDefault() > 100)
                {
                    ViewBagUtil.SetError(ViewBag, "มูลค่า % ของแต่ะละประเภท Liquidity รวมกันห้ามเกิน 100%", null);
                  //  return View("AddFixedIncome", model);

                }else if(model.Data.BondTypeId.GetValueOrDefault()!= 0)
                {

                    ReferenceCode refCode = oldData.ScreenData.BondType.FirstOrDefault(x => x.ID == model.Data.BondTypeId.GetValueOrDefault());
                    if (refCode != null && refCode.Key != "Discount" && model.Data.Coupon.GetValueOrDefault() == 0)//ฟิลด์ Bond Type โดยถ้าเป็น Discount Bond ฟิลด์ Coupon จะไม่เป็น required field หรือค่าเป็น 0
                    {

                        ViewBagUtil.SetError(ViewBag, "กรุณาระบุ Coupon ", null);

                    }
                    else
                    {
                        try
                        {

                            oldData = SaveOrUpdateDataFixedIncomeHeader(model);
                            oldData.UpdateMode = true;
                            ModelState.Clear();
                            ViewBagUtil.SetInfo(ViewBag, "การบันทึกสมบูรณ์", null);

                        }
                        catch (Exception ex)
                        {
                            ViewBagUtil.SetError(ViewBag, "การบันทึกผิดพลาด :" + ex.Message, null);
                            //  model = oldData;

                        }
                    }

                }
                else
                {

                    try
                    {

                        oldData = SaveOrUpdateDataFixedIncomeHeader(model);
                        oldData.UpdateMode = true;
                        ModelState.Clear();
                        ViewBagUtil.SetInfo(ViewBag, "การบันทึกสมบูรณ์", null);

                    }
                    catch (Exception ex)
                    {
                        ViewBagUtil.SetError(ViewBag, "การบันทึกผิดพลาด :" + ex.Message, null);
                        //  model = oldData;

                    }
                  
                }
            }
            else
            {
                ViewBagUtil.SetError(ViewBag, "Unknow Operation", null);
                return View("AddFixedIncome", model);
            }

            TempData["AddFixedIncomeModel"] = oldData;
            return View("AddFixedIncome", oldData);
            
        }


        private void CopyNewHeaderDataToOldModel(AddFixedIncomeModel newData)
        {
            var oldData = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];
            newData.Data.IssuerTerm = (decimal?)Calculator.CalFixIncomeIssueTerm(newData.Data.MaturityDate, newData.Data.IssueDate);
            newData.Data.IssuerTypeName = WebUtil.GetSelectionText(oldData.IssuerTypeList, newData.SelectedIssuerType);
            newData.Data.IssuerName = WebUtil.GetSelectionText(oldData.IssuerList, newData.SelectedIssuer.ToString());
            newData.Data.BondTypeName = WebUtil.GetSelectionText(oldData.BondTypeList, newData.SelectedBondType.ToString());
            newData.Data.GuarantorName = WebUtil.GetSelectionText(oldData.GuarantorList, newData.SelectedGuarantor.ToString());
            newData.Data.CompanyName = WebUtil.GetSelectionText(oldData.CompanyList, newData.SelectedCompany.ToString());
            newData.Data.InvolvedPartyTypeName = WebUtil.GetSelectionText(oldData.InvolvedPartyTypeNameList, newData.SelectedInvolvedPartyType.ToString());
            newData.Data.GuarantorTypeName = WebUtil.GetSelectionText(oldData.GuarantorTypeList, newData.SelectedGuarantorTypeID);

            if (newData.SelectedAssetClass.GetValueOrDefault() != 0)
            {
                AssetClass asset = oldData.ScreenData.AssetClass.Where(x => x.AssetClassID == newData.SelectedAssetClass.GetValueOrDefault()).FirstOrDefault();
                if (asset != null)
                    newData.Data.AssetClassEN = asset.AssetClassEN;
            }
            string creUser = oldData.Data.CreateUserId;
            DateTime? creDate = oldData.Data.CreateTs;
            string updateUser = oldData.Data.UpdateUserId;
            DateTime? updateDate = oldData.Data.UpdateTs;
            oldData.Data = newData.Data;
            oldData.Data.CreateUserId = creUser;
            oldData.Data.CreateTs = creDate;
            oldData.Data.UpdateUserId = updateUser;
            oldData.Data.UpdateTs = updateDate;
            oldData.RatingHistory = newData.RatingHistory;
           // oldData.Data.RiskLevel = newData.Data.RiskLevel;
            oldData.InvolvedPartyTypeNo = newData.InvolvedPartyTypeNo;
            oldData.InvolvedPartyTypeReferance = newData.InvolvedPartyTypeReferance;
            oldData.InvolvedPartyTypeNo = newData.InvolvedPartyTypeNo;
            oldData.IssueCreditAgencyForeign = newData.IssueCreditAgencyForeign;
            oldData.IssuerCreditAgencyForeign = newData.IssuerCreditAgencyForeign;
            oldData.GuarantorCreditAgencyForeign = newData.GuarantorCreditAgencyForeign;


            oldData.RatingHistory.IssueRating = newData.RatingHistory.IssueRating;
            oldData.RatingHistory.IssueCreditAgency = newData.RatingHistory.IssueCreditAgency;
            oldData.RatingHistory.IssueUpdateDate = newData.RatingHistory.IssueUpdateDate;
            oldData.RatingHistory.IssuerRating = newData.RatingHistory.IssuerRating;
            oldData.RatingHistory.IssuerCreditAgency = newData.RatingHistory.IssuerCreditAgency;
            oldData.RatingHistory.IssuerUpdateDate = newData.RatingHistory.IssuerUpdateDate;
            oldData.RatingHistory.GuarantorRating = newData.RatingHistory.GuarantorRating;
            oldData.RatingHistory.GuarantorCreditAgency = newData.RatingHistory.GuarantorCreditAgency;
            oldData.RatingHistory.GuarantorUpdateDate = newData.RatingHistory.GuarantorUpdateDate;

            oldData.RatingHistory.IssueCreditAgencyCountry = oldData.IssueCreditAgencyForeign;
            oldData.RatingHistory.IssuerCreditAgencyCountry = oldData.IssueCreditAgencyForeign;
            oldData.RatingHistory.GuarantorCreditAgencyCountry = oldData.GuarantorCreditAgencyForeign;
            if (String.IsNullOrEmpty(oldData.RatingHistory.CreateUserId))
            {
                oldData.RatingHistory.CreateUserId = SessionManager.UserID(Session);
            }
        }

        /// <summary>
        /// insert or update header
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private AddFixedIncomeModel SaveOrUpdateDataFixedIncomeHeader(AddFixedIncomeModel model)
        {

            var oldData = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];
          //  InvolvedPartyType involve = model.ScreenData.InvolvedPartyType.Where(X => X.InvolvedPartyTypeId == model.SelectedInvolvedPartyType.GetValueOrDefault()).SingleOrDefault();
            //if (model.Data != null && model.Data.InvolvedPartyTypeId.HasValue)
            //{
            //    InvolvedPartyType involed = model.ScreenData.InvolvedPartyType.Where(x => x.InvolvedPartyTypeId == model.Data.InvolvedPartyTypeId.GetValueOrDefault()).SingleOrDefault();
            //    if (involed != null)
            //    {
            //        oldData.InvolvedPartyTypeNo = involed.InvolvedPartyTypeCode;
            //        oldData.InvolvedPartyTypeReferance = involed.InvolvedPartyTypeReference;
            //    }
            //}
       

            FixIncomeSecuritiesDTO dto = new FixIncomeSecuritiesDTO();
            if (model.UpdateMode)
            {
                //dto  =  new FixIncomeSecuritiesDTO();
                //  dto = data.ScreenData.FixIncomeSecuritiesDTO;
                dto.Header = oldData.Data;
               
                dto.Header.CompanyId = model.SelectedCompany;
                dto.Header.IssuerTerm = model.Data.IssuerTerm;

                dto.Header.IssuerTypeName = model.Data.IssuerTypeName;
                dto.Header.IssuerName = model.Data.IssuerName;
                dto.Header.BondTypeName = model.Data.BondTypeName;
                dto.Header.GuarantorName = model.Data.GuarantorName;
                dto.Header.CompanyName = model.Data.CompanyName;
                dto.Header.InvolvedPartyTypeName = model.Data.InvolvedPartyTypeName;
                dto.Header.GuarantorTypeName = model.Data.GuarantorTypeName;

                dto.Header.MaturityStatus = model.Data.MaturityStatus;
                //model.Data.MaturityStatus
                dto.Header.FixedIncomeFullnameEN = model.Data.FixedIncomeFullnameEN;
                dto.Header.FixedIncomeFullnameTH = model.Data.FixedIncomeFullnameTH;
                dto.Header.AssetClassID = model.Data.AssetClassID;
                dto.Header.AssetClassEN = model.Data.AssetClassEN;
                dto.Header.TransactionType = model.Data.TransactionType;
                dto.Header.IssuerId = model.SelectedIssuer;
                dto.Header.IssuerTypeId = DataConverter.ConvertStringToIntNull(model.SelectedIssuerType);
                dto.Header.Symbol = model.Data.Symbol;
                dto.Header.GuarantorTypeID = DataConverter.ConvertStringToIntNull(model.SelectedGuarantorTypeID);
                dto.Header.GuarantorId = model.SelectedGuarantor;
                dto.Header.GuarantorOtherName = model.Data.GuarantorOtherName;
                dto.Header.IsinCode = model.Data.IsinCode;
                dto.Header.BondTypeId = model.SelectedBondType;
                dto.Header.ListedStatus = model.SelectedListedStatus;
                dto.Header.NumberTime = model.Data.NumberTime;
                dto.Header.InitialParUnit = model.Data.InitialParUnit;
                //dto.Header.Redempton=model.SelectedRedempton;
                
                dto.Header.CurrentParUnit = model.Data.CurrentParUnit;
                dto.Header.IssueSize = model.Data.IssueSize;
                dto.Header.Coupon = model.Data.Coupon;
                dto.Header.IssueDate = model.Data.IssueDate;
                dto.Header.CouponPaymentDate = model.Data.CouponPaymentDate;
                dto.Header.MaturityDate = model.Data.MaturityDate;
                dto.Header.CalculationMethod = model.SelectedCalculationMethod;
                dto.Header.PaymentFrequency = model.Data.PaymentFrequency;
                dto.Header.RiskLevel = model.Data.RiskLevel;
                dto.Header.LiquidityTierIPercent = model.Data.LiquidityTierIPercent;
                dto.Header.LiquidityTierIiPercent = model.Data.LiquidityTierIiPercent;
                dto.Header.LiquidityLowLiquidityPercent = model.Data.LiquidityLowLiquidityPercent;
                dto.Header.InvolvedPartyTypeId = model.Data.InvolvedPartyTypeId;

                dto.RatingHistory = oldData.RatingHistory;
                //dto.RatingHistory.IssueRating = model.RatingHistory.IssueRating;
                //dto.RatingHistory.IssueCreditAgency = model.RatingHistory.IssueCreditAgency;
                //dto.RatingHistory.IssueUpdateDate = model.RatingHistory.IssueUpdateDate;
                //dto.RatingHistory.IssuerRating = model.RatingHistory.IssuerRating;
                //dto.RatingHistory.IssuerCreditAgency = model.RatingHistory.IssuerCreditAgency;
                //dto.RatingHistory.IssuerUpdateDate = model.RatingHistory.IssuerUpdateDate;
                //dto.RatingHistory.GuarantorRating = model.RatingHistory.GuarantorRating;
                //dto.RatingHistory.GuarantorCreditAgency = model.RatingHistory.GuarantorCreditAgency;
                //dto.RatingHistory.GuarantorUpdateDate = model.RatingHistory.GuarantorUpdateDate;
                if (String.IsNullOrEmpty(dto.RatingHistory.CreateUserId))
                {
                    dto.RatingHistory.CreateUserId = SessionManager.UserID(Session);
                }
                dto.Header.UpdateUserId = SessionManager.UserID(Session);
                oldData.Data = dto.Header;
                oldData.RatingHistory = dto.RatingHistory;
                dto = ServiceFactory.GetService().UpdateFixIncomeHeader(dto);
                oldData.Data = dto.Header;
                oldData.RatingHistory = dto.RatingHistory;
            }
            else
            {
                dto.Header = model.Data;
                dto.Header.CreateUserId = SessionManager.UserID(Session);
                dto.RatingHistory = model.RatingHistory;
                dto.RatingHistory.CreateUserId = SessionManager.UserID(Session);
                oldData.Data = dto.Header;
                oldData.RatingHistory = dto.RatingHistory;
                dto = ServiceFactory.GetService().InsertFixIncomeHeader(dto);
                oldData.Data = dto.Header;
                oldData.RatingHistory = dto.RatingHistory;
            }
           
           
            return oldData;
        }

        #endregion

        #region Purchase

        public ActionResult CouponTableAndAmortize(int purchaseID)
        {
            CouponTableAndAmortizeModel model = new CouponTableAndAmortizeModel();
            try
            {
                AmortizeScreenData data = ServiceFactory.GetService().GenerateAmortize(purchaseID);
                model.AmortizeData = data;
            }
            catch (Exception ex)
            {

                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["CouponTableAndAmortizeModel"] = model;
            return View(model);
        }

        [HttpPost]
        public ActionResult CouponTableAndAmortize(CouponTableAndAmortizeModel model)
        {
            CouponTableAndAmortizeModel oldModel = (CouponTableAndAmortizeModel)TempData["CouponTableAndAmortizeModel"];
            if (!String.IsNullOrEmpty(model.BtnExportExcel))
            {
                String fileName = ExportAmortizeExcel(oldModel);
                String link = ConfigurationManager.AppSettings["ExcelServiceOutputUrl"] + fileName;
                return Redirect(link);
            }
            else
            {
                ViewBagUtil.SetError(ViewBag, "Unknow operation", null);
            }
            TempData["CouponTableAndAmortizeModel"] = oldModel;
            return View(oldModel);
        }

        private String ExportAmortizeExcel(CouponTableAndAmortizeModel oldModel)
        {
            if (oldModel.AmortizeData == null)
                throw new Exception("CouponTableAndAmortizeModel lost (ExportExcel)");
            ExcelWSService.ExcelWSClient client = new ExcelWSService.ExcelWSClient();
            client.Endpoint.ListenUri = new Uri(ConfigurationManager.AppSettings["ExcelServiceUrl"]);
            ExcelWSService.valueClass header = new ExcelWSService.valueClass();
            header.string1 = oldModel.Symbol;
            header.string2 = oldModel.AmortizeData.AmortizeHeader.TradeDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.string3 = oldModel.AmortizeData.AmortizeHeader.MaturityDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.double1 = (double)oldModel.AmortizeData.AmortizeHeader.ParValue.GetValueOrDefault();
            header.double2 = (double)oldModel.AmortizeData.AmortizeHeader.CleanPrice.GetValueOrDefault();
            header.double3 = (double)oldModel.AmortizeData.AmortizeHeader.DiscountPremium.GetValueOrDefault();
            header.double4 = (double)oldModel.AmortizeData.AmortizeHeader.AI.GetValueOrDefault();
            header.double5 = (double)oldModel.AmortizeData.AmortizeHeader.GrossPrice.GetValueOrDefault();
            header.double6 = (double)oldModel.AmortizeData.AmortizeHeader.ParValue.GetValueOrDefault();
            header.double7 = (double)oldModel.AmortizeData.AmortizeHeader.BookValue.GetValueOrDefault();
            header.double8 = (double)oldModel.AmortizeData.AmortizeHeader.IrrPerDay.GetValueOrDefault();
            header.double9 = (double)oldModel.AmortizeData.AmortizeHeader.Coupon.GetValueOrDefault();
            header.double10 = (double)oldModel.AmortizeData.AmortizeHeader.Yield.GetValueOrDefault();



            List<ExcelWSService.valueClass> detail = new List<ExcelWSService.valueClass>();
            foreach (var item in oldModel.AmortizeData.AmortizeDetailList)
            {
                ExcelWSService.valueClass value = new ExcelWSService.valueClass();
                value.double1 = item.Period.GetValueOrDefault();
                value.string1 = item.AmortizeDate.GetValueOrDefault().ToString("dd/MM/yyyy");
                value.double2 = item.NOOFDays.GetValueOrDefault();
                value.double3 = (double)item.Coupon.GetValueOrDefault();
                value.double4 = (double)item.Interest.GetValueOrDefault();
                value.double5 = (double)item.AmortiseOFInterest.GetValueOrDefault();
                value.double6 = (double)item.DiscountPremium.GetValueOrDefault();
                value.double7 = (double)item.BookValue.GetValueOrDefault();


                detail.Add(value);
            }



            return client.export1("amortize_01", header, detail.ToArray());
        }
        //public ActionResult GetPayValue(int? unit, decimal? par)
        //{
        //    if (unit == null || par == null)
        //        return null;
        //    var parvalue = unit.GetValueOrDefault()*par.GetValueOrDefault();
        //    var model = (AddFixedIncomePurchaseModel)TempData["AddFixedIncomePurchaseModel"];
        //    model.Purchase.ParValue = parvalue;
        //    TempData["AddFixedIncomePurchaseModel"] = model;
        //    return Json(new { ParValue = parvalue });
        //}

        /// <summary>
        /// หน้า add purchase
        /// </summary>
        public ActionResult AddFixedIncomePurchase(int fixedIncomeID)
        {
          var service=  ServiceFactory.GetService();

          var model = new AddFixedIncomePurchaseModel();
          try
          {
              model.AssignComboboxData(service.GetFixIncomePurchaseScreenData());
              model.HeaderDto =service.GetFixIncomeHeaderByID(fixedIncomeID);
              model.TIME2MATURE = WebUtil.NonApplicableIfZero(Calculator.CalTime2Mature(model.HeaderDto.Header.MaturityDate.GetValueOrDefault(), WebUtil.SystemDate));
          }
          catch (Exception ex)
          {
              ViewBagUtil.SetError(ViewBag, ex.Message, null);
          }


            TempData["AddFixedIncomePurchaseModel"] = model;
            return View(model);
        }
        /// <summary>
        /// หน้า edit purchase
        /// </summary>
        public ActionResult EditPurchase(int purchaseID)
        {
            var service = ServiceFactory.GetService();

            var model = new AddFixedIncomePurchaseModel();
            try
            {
                var dto = service.GetFixIncomePurchaseByID(purchaseID);
                model.AssignComboboxData(service.GetFixIncomePurchaseScreenData());
                model.Purchase = dto.Purhcase;
                model.HeaderDto = dto.Header;
                model.TIME2MATURE = WebUtil.NonApplicableIfZero(Calculator.CalTime2Mature(dto.Header.Header.MaturityDate.GetValueOrDefault(), WebUtil.SystemDate));
            }
            catch (Exception ex)
            {
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            model.UpdateMode = true;
            TempData["AddFixedIncomePurchaseModel"] = model;
            return View("AddFixedIncomePurchase", model);
        }

        decimal? CalTime2Mature(DateTime? matureityDate)
        {
            /* case when 
                    FIXINCOMESECURITIES_HEADER.MATURITY_DATE <= getdate() then 0 		
               else 		
                    convert(decimal(12,2), DATEDIFF(m, FIXINCOMESECURITIES_HEADER.MATURITY_DATE , getdate())/12.00)
             */
            if (matureityDate.HasValue)
            {
                var start = matureityDate.GetValueOrDefault();
                DateTime end = ServiceFactory.GetService().GetSystemDateTime();
                if (start <= end)
                    return 0;
                //find of diff month
                var diffMonths = (end.Month + end.Year * 12) - (start.Month + start.Year * 12) + 1;
                //find TIME2MATURE
                return diffMonths / 12;
            }
            return null;
        }

        // init model สำหรับ insert or update purchase
        //AddFixedIncomePurchaseModel InitAddFixedIncomePurchaseModel(AddFixedIncomePurchaseModel model)
        //{
        //    if (model == null)
        //        model = new AddFixedIncomePurchaseModel();

        //    var payTypes = ServiceFactory.GetService().GetAllPaymentTypes();
        //    if (payTypes == null)
        //    {
        //        model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = "Bathnet", Value = "1" });
        //        model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = "Cheque", Value = "2" });
        //        model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = "NET", Value = "3" });
        //        model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = "Rollover", Value = "4" });
        //    }
        //    else
        //    {
        //        foreach (var o in payTypes)
        //        {
        //            model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = o.PaymentTypeName, Value = o.PaymentTypeId.ToString() });
        //        }
        //    }

        //    //select from COUNTERPARTY.COUNTERPARTY_NAME
        //    var cntParties = ServiceFactory.GetService().GetAllCounterPaties();
        //    if (cntParties == null)
        //    {
        //        model.CounterPartyList.Add(item: new SelectListItem() { Selected = false, Text = "HSBC", Value = "1" });
        //        model.CounterPartyList.Add(item: new SelectListItem() { Selected = false, Text = "BBL", Value = "2" });
        //        model.CounterPartyList.Add(item: new SelectListItem() { Selected = false, Text = "KL", Value = "3" });
        //    }
        //    else
        //    {
        //        foreach (var o in cntParties)
        //        {
        //            model.CounterPartyList.Add(item: new SelectListItem() { Selected = false, Text = o.CounterpartiesCodeName, Value = o.CounterpartiesId.ToString() });
        //        }
        //    }

        //    return model;
        //}

        /// <summary>
        /// action สำหรรับ insert or update purchase
        /// </summary>
        [HttpPost]
        public ActionResult ExecuteForAddFixedIncomePurchase(AddFixedIncomePurchaseModel model, object arg)
        {
            var oldModel = (AddFixedIncomePurchaseModel)TempData["AddFixedIncomePurchaseModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SubmitBtn))
                    {
                        if (oldModel.ScreenData != null)
                        {
                            if (model.Purchase.CounterpartyId.HasValue)
                            model.Purchase.CounterpartyName = oldModel.ScreenData.CounterPartiesList.Where(x => x.CounterpartiesId == model.Purchase.CounterpartyId.Value).Select(x => x.CounterpartiesNameEn).SingleOrDefault();
                            if (model.Purchase.TypeofpaymentId.HasValue)
                            model.Purchase.TypeofpaymentName = oldModel.ScreenData.PaymentTypeList.Where(x => x.PaymentTypeId == model.Purchase.TypeofpaymentId.Value).Select(x => x.PaymentTypeName).SingleOrDefault();
                        }
                        model.Purchase.FixincomesecuritiesHeaderId = model.Header.FixincomesecuritiesHeaderId;
                        model.Purchase.CreateTs = oldModel.Purchase.CreateTs;
                        model.Purchase.CreateUserId = oldModel.Purchase.CreateUserId;
                        model.Purchase.UpdateTs = oldModel.Purchase.UpdateTs;
                        model.Purchase.UpdateUserId = oldModel.Purchase.UpdateUserId;
                        oldModel.Purchase = model.Purchase;
                        if (model.UpdateMode)
                        {
                            model.Purchase.UpdateUserId = SessionManager.UserID(Session);
                            oldModel.Purchase = ServiceFactory.GetService().UpdateFixincomesecuritiesPurchase(model.Purchase);
                        }
                        else
                        {
                            model.Purchase.CreateUserId = SessionManager.UserID(Session);
                            oldModel.Purchase = ServiceFactory.GetService().InsertFixedIncomePurchase(model.Purchase);
                        }
                        oldModel.UpdateMode = true;
                        ViewBagUtil.SetInfo(ViewBag, "การทำงานสมบูรณ์", null);
                        ModelState.Clear();
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);

                }
            }
            TempData["AddFixedIncomePurchaseModel"] = oldModel;
            return View("AddFixedIncomePurchase", oldModel);
        }

        #endregion


        #endregion


        #region Equity Securities
        //add logic for "Equity Securities" here


        #endregion

        #region Unit Trust
        //add logic for "Unit Trust" here


        #endregion

        #region Derivatives Securities
        //add logic for "Derivatives Securities" here


        #endregion

        #region Loans
        //add logic for "Loans" here


        #endregion

        #region Deposit at Financial Institutions
        //add logic for "Deposit at Financial Institutions" here


        #endregion


    }
}
